package v1

import (
	"github.com/gin-gonic/gin"
	"os"
	"net/http"
	"hytx_media/pkg/e"
	"bytes"
	"hytx_media/pkg/upload"
		"encoding/json"
)

const (
	ActionConfig      = "config"
	ActionListimage   = "listimage"
	ActionListFile    = "listfile"
	ActionUploadImage = "uploadimage"
	ActionUploadFile  = "uploadfile"
)


func UEditor(c *gin.Context) {
	action := c.Query("action")
	method := c.Request.Method
	if method == "GET" && action == ActionConfig {
		config(c)
		return
	}
	if method == "POST" {
		switch action {
		case ActionUploadImage:
			uploadImage(c)
			return
		}
	}
	c.JSON(http.StatusMethodNotAllowed, gin.H{
		"code" : http.StatusMethodNotAllowed,
		"msg" : "请求方法错误请使用post",
	})
}

func config (c *gin.Context) {
	file, err := os.Open("conf/ueditor.json")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": e.Error,
			"msg": e.GetMsg(e.Error),
		})
		return
	}
	defer file.Close()
	buf := bytes.NewBuffer(nil)
	buf.ReadFrom(file)
	config := buf.String()
	callback := c.Query("callback")
	if callback != "" {
		c.String(http.StatusOK, callback + "(" + config + ")")
	}else{
		c.String(http.StatusOK, config)
	}
}

func uploadImage(c *gin.Context) {
	img := upload.Image(c)
	if img["code"] != 200{
		c.JSON(img["code"].(int), map[string]interface{}{
			"state": img["msg"],
			"url": nil,
			"title": nil,
			"original": nil,
			"type": nil,
			"size": nil,
		})
		return
	}
	data := map[string]interface{}{
		"state": "SUCCESS",
		"url": upload.GetImageFullUrl(img["data"].(string)),
		"title": img["data"],
		"original": img["data"],
	}
	str, _ := json.Marshal(data)
	c.String(http.StatusTemporaryRedirect, string(str))
	return
}